package com.smart.core.starter.model;

import com.smart.core.starter.exception.IError;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.Serializable;

 /**
  * 通用返回结果
  * @author guxiaobai
  * @date 2018/11/28 21:05
  */
@ToString
public class R<T> implements Serializable {
	private static final int SUCCESS = 0;
	private static final int ERROR = 1;
	private static final String ERROR_MSG = "error";
	private static final long serialVersionUID = 1L;
	@Getter
	@Setter
	private String msg = "success";

	@Getter
	@Setter
	private int code = SUCCESS;

	@Getter
	@Setter
	private T data;

	 public R() {
		super();
	}

	 public R(T data) {
		super();
		this.data = data;
	}

	 public R(T data, String msg) {
		super();
		this.data = data;
		this.msg = msg;
	}

	 public R(int code, String msg, T data) {
		this.data = data;
		this.msg = msg;
		this.code = code;
	}

	 public R(Throwable e) {
		super();
		this.msg = e.getMessage();
		this.code = ERROR;
	}

	 public static <T> R<T> success() {
		 return new R<>();
	}


	 public static <T> R<T> error() {
		 return new R<>(ERROR, ERROR_MSG, null);
	 }

	 public static <T> R<T> error(IError error) {
		 return new R<>(error.getCode(), error.getMsg(), null);
	 }

	 public static <T> R<T> success(T data) {
		 return new R<>(data);
	 }

	 public static <T> R<T> error(int code, String msg) {
		 return new R<>(code, msg, null);
	 }

	 public static <T> R<T> error(String msg) {
		 return new R<>(ERROR, msg, null);
	}
}
